package com.briup.server;

import com.briup.Configuration;
import com.briup.ConfigurationImpl;
import com.briup.entity.Environment;
import com.briup.support.ConfigurationAware;
import com.briup.support.PropertiesAware;
import com.briup.util.Log;
import com.briup.util.LogImpl;

import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 实现服务器功能 接收客户端发送的数据
 */
public class ServerImpl implements Server , PropertiesAware, ConfigurationAware {
    private ServerSocket server;
    private int port;
    private Log log;
    private   DBStore store;

    @Override
    /**
     * 接收客户端发送的(集合对象)数据
     */
    public void receive() throws Exception {
        //创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        //创建服务器
        server = new ServerSocket(port);
        log.info("服务器已经启动  等待客户端连接");
        //等待客户端连接 保证服务器不宕机
        while (true) {
            //有客户端来连接  创建套接字
            Socket socket = server.accept();
            log.info("有客户端来连接 "+socket.getInetAddress());
            //将任务提交给线程池
            pool.submit(() -> {
                try {
                    //创建对象输入流  包装流
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    //接收数据
                    List<Environment> list = (List<Environment>) ois.readObject();
                    log.info("服务器接收到的数据：" + list.size());
                    log.info("准备入库");
                    //入库
                    store.saveDB(list);
                    log.info("入库成功");
                    //关闭资源
                    ois.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });


        }
    }

    @Override
    /**
     * 关闭 服务器
     */
    public void shutdown() throws Exception {
        if (server != null)
            server.close();
    }

    @Override
    public void init(Properties properties) throws Exception {
       port=Integer.parseInt( properties.getProperty("port"));
    }

    @Override
    public void setConfiguration(Configuration configuration) throws Exception {
      log=configuration.getLogger();
      store=configuration.getDbStore();
    }
}
